import { message } from 'ant-design-vue'
import axios from 'axios'

import { useUserStore } from '@/store'

const ajax = axios.create({
  baseURL: '/api'
})

ajax.interceptors.request.use(req => {
  const userStore = useUserStore()

  if (userStore.token) {
    req.headers!['Authorization'] = `Bearer ${userStore.token}`
  }

  return req
})

ajax.interceptors.response.use(
  res => {
    const url = res.config.url

    if (url?.endsWith('/export')) {
      return res
    }

    return res.data.data
  },
  err => {
    const res = err.response

    if (res.status === 422) {
      if (res.data.message) {
        message.error(res.data.message, 1.5)
      } else {
        const file = new FileReader()
        file.readAsText(res.data)
        file.onload = function () {
          const res = JSON.parse(file.result as string)
          message.error(res.message, 1.5)
        }
      }
    } else {
      message.error(res.data.message, 1.5, () => {
        if (res.status === 401 || res.data.status === 401) {
          const userStore = useUserStore()

          userStore.clear().then(() => {
            location.reload()
          })
        }
      })
    }

    return Promise.reject(err)
  }
)

export { ajax }
